package cn.tedu.v5;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * 多人聊天室 Version 5      登录与退出   功能：可以加在v3
 * Version 6  在线用户列表 统计上线名称
 *            消息转发 --交互--服务器 客户端文字
 *
 *
 *
 */
public class Server {
    private ServerSocket serverSocket;
    private static final Integer PORT = 9908;
    private List<PrintWriter> allOut=new ArrayList<>();
    //1.私有化属性：存账号密码
    //+++++++++++++++
    private   Map<String,String> uerDatabase;

    public Server() {
        try {
            //2创建Map对象
            uerDatabase=new HashMap<>();
            uerDatabase.put("易易","121511");
            uerDatabase.put("想想","101211");

            serverSocket = new ServerSocket(PORT);
        } catch (BindException e) {
            System.out.println("请检查端口号，被占用");
        } catch (IOException e) {
            System.out.println("客户端没有链接上");
        }
    }


    public void start() {


        try {
            while (true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();

                new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            System.out.println("客户端链接断开链接");
        } finally {
            if (serverSocket != null && serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败");
                }
                System.out.println("服务器关闭成功");
            }
        }
    }


    public static void main(String[] args) {
        new Server().start();
    }


    private synchronized void broadcastMessage(String message){

        for (PrintWriter pw:allOut){
            pw.println("消息广播"+message);
        }
    }
    //++++++++++++++

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String ip;
        private PrintWriter pw;
        private BufferedReader br;
        //线程中：确定那个客户端--赋予功能
        private String username;
        private String password;

        public ClientHandler(Socket s) {

            this.socket = s;
            ip = socket.getInetAddress().getHostAddress();
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);

            synchronized (allOut){
                allOut.add(pw);
            }

            } catch (IOException e) {
                System.out.println("客户端断开连接");
            }
        }
        //5.5因为用户账号可能很多，封装Login传入参数判读
        private boolean Login(String user,String pass){
            return uerDatabase.containsKey(user)&&uerDatabase.get(user).equals(pass);
        }
        //6handleChat封装：读写功能---放进线程中
        private void handleChat(){
            new Thread(() -> {
                try {
                    String message;
                    while ((message = br.readLine()) != null) {
                        System.out.println(username + "客户端：" + message);
                        System.out.print("服务器请输入：");
                        if (message.equalsIgnoreCase("exit")){

                            break;
                        }
                    }
                } catch (IOException e) {
                    System.out.println("客户端发来的消息断开了");
                }
            }).start();

            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("服务器请输入：");
                String sme = input.nextLine();
                pw.println("服务器端说：" + sme);
                if (sme.equalsIgnoreCase("exit")){
                    pw.println(username+"我退出聊天室了~~~~~~~");
                    break;
                }

            }
        }
        public void run() {
            try {
                //5.当客户端进行读写功能前加入登录功能
                //交互问题：服务器---客户端发送：文本
                //        客户端---服务器接受：文本
                //5.1向客户端发送一个提示消息：请输入用户名
                pw.println("请输入用户名");
                //5.2客户端输入账号【服务端读取】
                username=br.readLine();
                pw.println("请输入密码");
                password=br.readLine();

                //5.3服务器端判断账号
                //5.4用户很多个，封装方法Login：判断账号密码

                if (Login(username,password)){
                    pw.println("登陆成功，欢迎进入晴天聊天室");
                    //聊天功能   封装方法：读写功能 handleChat
                    handleChat();
                }else {
                    pw.println("登录失败，用户名或者密码错误");
                    socket.close();//关闭
                }

            } catch (IOException e){
                System.out.println("服务器端写出问题！！！");
            }
            finally {
                synchronized (allOut){
                    allOut.remove(pw);
                }


                if (pw != null)
                    pw.close();

                if (br != null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        System.out.println("读入流断开连接");
                    }

                if (socket != null && !socket.isClosed()) {
                    System.out.println(username + "客户端退出服务器链接");
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println(ip + "客户端退出服务器链接");
                    }
                }
            }
        }
    }
}
